package com.tduck.cloud.api.web.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tduck.cloud.account.entity.RoleEntity;
import com.tduck.cloud.account.entity.UserEntity;
import com.tduck.cloud.account.entity.UserRoleEntity;
import com.tduck.cloud.account.entity.enums.AccountChannelEnum;
import com.tduck.cloud.account.service.RoleService;
import com.tduck.cloud.account.service.UserRoleService;
import com.tduck.cloud.account.service.UserService;
import com.tduck.cloud.api.util.UipUtils;
import com.tduck.cloud.common.constant.UipConstant;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户异步工作
 *
 * @author Guard Baby
 * @date 2023/08/11
 */

@Slf4j
public class UserAsyncJob implements Job {
    @Resource
    private UserService userService;
    @Resource
    private UipUtils uipUtils;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;

    private final static String PT_USER_CODE = "pt";


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        String parameter = jobDataMap.getString("parameter");
        log.info("^^^^^^^^^^^友空间人员同步任务开始^^^^^^^^^^");
        int pageNo = 1;
        int pageSize = 500;
        List<UserEntity> userEntityList = new ArrayList<>();
        while (true) {
            String result = uipUtils.queryStaffList(pageNo++, pageSize, null);
            JSONObject resultJson = JSONObject.parseObject(result);
            String code = resultJson.getString("code");
            if (UipConstant.SUCCESS_CODE.equals(code)) {
                JSONObject data = resultJson.getJSONObject("data");
                JSONArray recordList = data.getJSONArray("recordList");
                if (CollUtil.isEmpty(recordList)) {
                    log.error("本次未获取到数据");
                    return;
                }
                log.info("本次获取到数据{}条", recordList.size());
                for (int i = 0; i < recordList.size(); i++) {
                    JSONObject d = recordList.getJSONObject(i);
                    UserEntity userEntity = new UserEntity();
                    userEntity.setYhtId(d.getString("user_id"));
                    userEntity.setId(d.getLong("id"));
                    userEntity.setName(d.getString("name"));
                    userEntity.setOrgId(d.getLong("dept_id"));
                    userEntity.setEmail(d.getString("email"));
                    userEntity.setCode(d.getString("code"));
                    userEntity.setRegChannel(AccountChannelEnum.UIP);
                    userEntity.setDr(d.getInteger("dr"));
                    userEntity.setPhoneNumber(d.getString("mobile"));
                    if (Objects.isNull(userService.getById(userEntity.getId())) || Objects.equals(parameter, "1")) {
                        String randomPassword = RandomUtil.randomString(6);
                        log.info("{}的随机密码：{}", userEntity.getName(), randomPassword);
                        userEntity.setPassword(DigestUtil.sha256Hex(randomPassword));
                        userEntity.setPlainText(randomPassword);
                    }
                    if (userEntity.getDr() != 0 || Objects.isNull(userEntity.getYhtId())) {
                        continue;
                    }
                    userEntityList.add(userEntity);
                }
                int endPageIndex = data.getIntValue("endPageIndex");
                if (pageNo > endPageIndex) {
                    break;
                }
            }
        }
        if (CollUtil.isNotEmpty(userEntityList)) {
            userService.saveOrUpdateBatch(userEntityList);
            List<Long> userIds = userEntityList.stream().map(UserEntity::getId).collect(Collectors.toList());
            List<UserRoleEntity> userRoleEntities = new ArrayList<>();
            RoleEntity roleEntity = roleService.query().eq("code", PT_USER_CODE).one();
            for (Long userId : userIds) {
                if (userRoleService.query().eq("user_id", userId).count() == 0) {
                    UserRoleEntity userRoleEntity = new UserRoleEntity();
                    userRoleEntity.setUserId(userId);
                    userRoleEntity.setRoleId(roleEntity.getId());
                    userRoleEntities.add(userRoleEntity);
                }
            }
            userRoleService.saveBatch(userRoleEntities);
        }
        log.info("^^^^^^^^^^^友空间人员同步任务结束^^^^^^^^^^");
    }
}
